import React, { Component } from 'react';
import Taro from '@tarojs/taro';
import Skeleton from 'taro-skeleton';
import {Block, View, Image, Text} from '@tarojs/components';
import {AtLoadMore} from 'taro-ui';
import {http} from '../../utils/http'
import { FETCH_SECKILL_LIST, ADD_SHARE_VOLUME } from '../../constants/api'
import {getPoster} from '../../utils/poster.service'
import {gotoPage } from '../../utils/tools'
import {h5Wx} from "../../utils/h5.service";
import {user} from '../../utils/user.service';
import Float from '../../components/float/float';
import Share from '../../components/share/share';
import CountDown from "../../components/count-down/count-down-seckill";
import './index.scss';

const defaultAdverPic = "https://resource.ivcheng.com/upload/images/20221110/1668049211971_639.png";
const outSaleImg = "https://resource.ivcheng.com/upload/images/20221110/1668046531350_363.png";

interface StateType {
	loading: boolean
	loadMoreStatus: "more" | "loading" | "noMore"
}

export default class SeckillActive extends Component {
	constructor(props) {
		super(props);
	}

	state: StateType = {
		loading: false,
		loadMoreStatus: 'loading',
		seckillList: [],
		seckillStatus: "",
		seckillTime: null,
		adverPic: "",
		sell_status: "",
		goodId: "",
		linkUri: "",
		isUser: true,
		isLogin: false,
	}

	page = 1

	async componentDidShow() {
		const isLogin = await user.checkLogin();
		const { id } = Taro.getCurrentInstance().router.params;
		let link = `/common/seckill/index?id=${id}`;
        if (process.env.TARO_ENV === 'h5') {
            link = window.location.origin + link;
            const shareData = {
				title: "秒杀活动",
				desc: '',
				link,
				imgUrl: ""
			};
			h5Wx.share(shareData);
        }
        this.setState({linkUri: link, goodId: id, isLogin})
		await Taro.setNavigationBarTitle({
            title: '活动列表'
        })
		this.getList();
	}

	async getList(page = 1) {
		const { name, id } = Taro.getCurrentInstance().router.params;
		const params = {
			page,
			length: 10,
			name,
			id
		};
		const result = await http.HGet(FETCH_SECKILL_LIST, params);
		const {
			data: {
				data: {
					id: seckill_id,
					goodslist,
					status,
					time,
					advertising,
					sell_status
				}
			}
		} = result;
		const seckillList = goodslist.map(item => ({
			...item,
			url: `/common/seckill/detail?itemId=${item.goods_id}&seckill_id=${seckill_id}`,
			img: item.seckill_img_url ? JSON.parse(item.seckill_img_url)[0].url : "",
		}))
		this.setState({
			seckillList,
			seckillStatus: status,
			seckillTime: time,
			adverPic: advertising,
			sell_status,
			loadMoreStatus: seckillList.length === 10 ? "more" : "noMore"
		})
	}

	onReachBottom() {
		/*if (this.state.loadMoreStatus != 'noMore') {
			this.setState({loadMoreStatus: 'loading'}, async () => {
				this.page++
				const goods = await this.getList(this.page)
				const old = this.state.seckillList
				this.setState({seckillList: [...old, ...goods]})
			})
		}*/
	}

	renderButton = (item) => {
		const { sell_status } = this.state;
		let domButton = null;

		if(sell_status === 0) {
			domButton = (
				<View className='seckill-btn seckill-btn-disabled'>即将开售</View>
			)
		}else if(sell_status === 1) {
			if(item.status === 0) {
				domButton = (
					<View className='seckill-btn seckill-btn-disabled'>已售罄</View>
				)
			}else if(item.status === 1) {
				domButton = (
					<View className='seckill-btn seckill-btn-active' onClick={() => this.viewDetail(item)}>立即抢购</View>
				)
			}
		}else {
			domButton = (
				<View className='seckill-btn seckill-btn-disabled'>已结束</View>
			)
		}

		return domButton;
	}

	handleInDjs = (flag) => {
		this.setState({timeStatus: flag})
	};

	viewDetail(item) {
		if(item.seckill_stock > 0) {
			gotoPage(item.url);
		}
	}

	onGetPoster = async () => {
		const { id } = Taro.getCurrentInstance().router.params;
        const { isLogin } = this.state;
        if (!isLogin) {
            await user.jumpLogin()
        }
        let link = `/common/seckill/index?id=${id}`;
        if (process.env.TARO_ENV === 'h5') {
            link = window.location.origin + link;
        }
        Taro.showLoading({title: '获取海报中...'});
        const poster = await getPoster('seckillList', id, link, "")
        // const poster = await getPoster(FETCH_SECKILL_POSTER, {path: link, id: goodSeckillId});
        if (poster) {
            http.get(ADD_SHARE_VOLUME, {category: 0})
            Taro.navigateTo({url: '/distributor/poster/poster?url=' + poster.url})
        } else {
            Taro.showToast({title: '获取海报失败！', icon: 'none'})
        }
        Taro.hideLoading();
    }

	render() {
		const { loading, loadMoreStatus, seckillList, seckillStatus, seckillTime, adverPic, linkUri, goodId, isUser } = this.state;

		return (
			<View className='seckill-list-page'>
				<View className='adver-pic'>
					<Image src={adverPic || defaultAdverPic} mode='aspectFill' className='imageStyle' />
					<View className='seckill-time'>
						<View className='count-down-wrap'>
							<View className='time-tips'>{ seckillStatus }</View>
							<CountDown time={seckillTime} isBGColor whiteSemicolon inDjs={this.handleInDjs} />
						</View>
					</View>
				</View>
				<Skeleton loading={loading} row={4} rowHeight={340} skeletonColor='#fff'>
					<View className='seckill-lists'>
						{
							seckillList.map((item, index) => (
								<View className='seckill-item'>
									<View className='items'>
										<View className='items-left' onClick={() => this.viewDetail(item)}>
											<Image mode='aspectFill' className='img' src={item.img} />
											{
												item.seckill_stock <= 0 &&
												<Block>
													<View className='seckill-img-mask'></View>
													<Image mode='aspectFit' className='img outsaleimg' src={outSaleImg} />
												</Block>
											}
										</View>

										<View className='items-right'>
											<View className='right-top' onClick={() => this.viewDetail(item)}>
												<View className='pro-name'>{item.seckill_goods_name}</View>
												{
													!!item.seckil_short_name &&
													<View className='sub-title'>{item.seckil_short_name}</View>
												}
											</View>
											{/*
												item.status !== "即将开售" &&
												<View className="seckill-progress">
													<AtProgress
														percent={item.progress}
														color='#ec5a50'
														stroke-width='16rpx'
														isHidePercent={true}
													/>
													<View className="progress-text">已抢{item.progress}%</View>
												</View>
											*/}
											<View className='end-flex'>
												<View className='right-price'>
													<View className='price' onClick={() => this.viewDetail(item)}>
														<View className='true-price font-family-price'>
															<Text className='font-family-price symbol'>￥</Text>
															<Float value={item.seckill_price} />
														</View>
														<View
  className='price-right font-family-price'
														>￥{item.market_price}</View>
													</View>
													{/*按钮*/}
													{ this.renderButton(item) }
												</View>
											</View>
										</View>
									</View>
								</View>
							))
						}
					</View>
					<AtLoadMore status={loadMoreStatus} noMoreText='' moreBtnStyle='border:none;' moreText='加载更多' />
				</Skeleton>
				<Share displayPoster page='seckillList' isUser={isUser} uuid={goodId} linkUri={linkUri} />
				{/*<View onClick={this.onGetPoster}>生成海报</View>*/}
			</View>
		)
	}
}
